import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_type_config.dart';
import 'package:largefriends/entity/entities/lf_bool_entity.dart';
import 'package:largefriends/net/lf_api_url.dart';
import 'package:largefriends/net/lf_dio_util.dart';
import 'package:largefriends/res/lf_color.dart';
import 'package:largefriends/res/lf_double_ext.dart';
import 'package:largefriends/res/lf_fonts.dart';
import 'package:largefriends/res/lf_string_ext.dart';
import 'package:largefriends/res/lf_text_style.dart';
import 'package:largefriends/res/strings/lf_strings.dart';
import 'package:largefriends/utils/lf_keyboard.dart';
import 'package:largefriends/widgets/data_time_picker/flutter_datetime_picker.dart';
import 'package:largefriends/widgets/lf_button.dart';
import 'package:largefriends/widgets/lf_single_picker.dart';

import '../../../config/lf_config.dart';
import '../../../net/error_handle.dart';
import '../../../utils/lf_dialog_utils.dart';
import '../../../widgets/data_time_picker/src/datetime_picker_theme.dart';
import '../../../widgets/lf_auto_complete.dart';
import '../../../widgets/lf_text_label_filed.dart';
import '../lf_register_logic.dart';

class LfRegisterAccount extends StatefulWidget {
  const LfRegisterAccount({Key? key}) : super(key: key);

  @override
  _LfRegisterAccountState createState() {
    return _LfRegisterAccountState();
  }
}

class _LfRegisterAccountState extends State<LfRegisterAccount> {
  final LfRegisterLogic logic = Get.find();
  RxString nameTips = "".obs;
  RxString emailTips = "".obs;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      height: ScreenUtil().screenHeight,
      child: SingleChildScrollView(
        child: Column(
          children: [
            ShaderMask(
                shaderCallback: (Rect bounds) {
                  return LinearGradient(
                    begin: const Alignment(-0.5, -0.9),
                    end: const Alignment(0.5, 0.9),
                    colors: [
                      colorFF007F,
                      colorFF007F,
                      colorBF00FF,
                      colorBF00FF
                    ],
                  ).createShader(Offset.zero & bounds.size);
                },
                blendMode: BlendMode.srcATop,
                child: Text(
                  appName,
                  style: lfTextStyle(sp: 48.sp, fontFamily: fontYoungSerif),
                )),
            20.h.sbh,
            LfTextLabelFiled(
              textEditingController: logic.usernameController,
              isPassword: false,
              hintText: strUsername.tr,
              focusNode: logic.usernameFocusNode,
              prefixIcon: Icon(
                Icons.person,
                color: colorFF007F,
                size: 20.w,
              ),
              inputFormatters: [
                LengthLimitingTextInputFormatter(16),
                FilteringTextInputFormatter.allow(RegExp('[A-Za-z0-9]'))
              ],
              hintStyle: lfTextStyle(
                  sp: 14.sp,
                  fontFamily: fontRegular,
                  color: color210215.withAlpha(128)),
              inputStyle: lfTextStyle(sp: 14.sp, fontFamily: fontMedium),
              onChanged: (value) {
                logic.username.value = value;
                if (logic.username.value.isEmpty) {
                  nameTips.value = "";
                } else if (logic.username.value.length < 3) {
                  nameTips.value =
                      strCharactersMinimum.tr.replacePercentS(["3"]) ?? "";
                } else {
                  nameTips.value = '${logic.username.value.length}/16';
                }
              },
            ),
            5.h.sbh,
            Align(
              alignment: Alignment.bottomRight,
              child: Obx(() {
                return Text(
                  nameTips.value,
                  style: lfTextStyle(
                      sp: 12.sp, fontFamily: fontRegular, color: color210215),
                );
              }),
            ),
            6.h.sbh,
            autoCompleteWidget(
                onSelected: (String value) {
                  logic.email.value = value;
                },
                hintText: strEmail.tr,
                hintStyle: lfTextStyle(
                    sp: 14.sp,
                    fontFamily: fontRegular,
                    color: color210215.withAlpha(128)),
                inputStyle: lfTextStyle(sp: 14.sp, fontFamily: fontMedium),
                focusNode: logic.emailFocusNode,
                onChanged: (String value) {
                  logic.email.value = value;
                },
                controller: logic.emailController),
            5.h.sbh,
            Align(
              alignment: Alignment.bottomRight,
              child: Text(
                '',
                style: lfTextStyle(
                    sp: 12.sp, fontFamily: fontRegular, color: color210215),
              ),
            ),
            6.h.sbh,
            LfTextLabelFiled(
              textEditingController: logic.passwordController,
              isPassword: true,
              hintText: strPassword.tr,
              focusNode: logic.passwordFocusNode,
              prefixIcon: Icon(
                Icons.lock,
                color: colorFF007F,
                size: 20.w,
              ),
              inputFormatters: [
                LengthLimitingTextInputFormatter(16),
                FilteringTextInputFormatter.deny(RegExp('[ ]'))
              ],
              hintStyle: lfTextStyle(
                  sp: 14.sp,
                  fontFamily: fontRegular,
                  color: color210215.withAlpha(128)),
              inputStyle: lfTextStyle(sp: 14.sp, fontFamily: fontMedium),
              onChanged: (value) {
                logic.password.value = value;
              },
            ),
            5.h.sbh,
            Align(
              alignment: Alignment.bottomRight,
              child: Obx(() {
                var tips = "";
                if (logic.password.value.isEmpty) {
                  tips = "";
                } else if (logic.password.value.length < 6) {
                  tips = strCharactersMinimum.tr.replacePercentS(["6"]) ?? "";
                } else {
                  tips = '${logic.password.value.length}/16';
                }
                return Text(
                  tips,
                  style: lfTextStyle(
                    sp: 12.sp,
                    fontFamily: fontRegular,
                  ),
                );
              }),
            ),
            6.h.sbh,
            InkWell(
              child: LfTextLabelFiled(
                textEditingController: logic.genderController,
                isPassword: false,
                enable: false,
                hintText: strGender.tr,
                focusNode: logic.genderFocusNode,
                prefixIcon: Icon(
                  Icons.group_outlined,
                  color: colorFF007F,
                  size: 20.w,
                ),
                hintStyle: lfTextStyle(
                    sp: 14.sp,
                    fontFamily: fontRegular,
                    color: color210215.withAlpha(128)),
                inputStyle: lfTextStyle(sp: 14.sp, fontFamily: fontMedium),
                onChanged: (value) {},
              ),
              onTap: () {
                closeSoftKeyboard();
                showLfSinglePicker(
                    configTypeEnum: LfConfigTypeEnum.gender,
                    value: 0,
                    saveCallback: (value) {
                      logic.gender.value = value;
                      logic.genderController.text = TypeConfig().getValueByKey(
                        LfConfigTypeEnum.gender,
                        value,
                      );
                    });
              },
            ),
            5.h.sbh,
            Align(
              alignment: Alignment.bottomRight,
              child: Text(
                "",
                style: lfTextStyle(
                  sp: 12.sp,
                  fontFamily: fontRegular,
                ),
              ),
            ),
            6.h.sbh,
            InkWell(
              child: LfTextLabelFiled(
                textEditingController: logic.birthdayController,
                isPassword: false,
                enable: false,
                hintText: strBirthday.tr,
                focusNode: logic.birthdayFocusNode,
                prefixIcon: Icon(
                  Icons.date_range,
                  color: colorFF007F,
                  size: 20.w,
                ),
                hintStyle: lfTextStyle(
                    sp: 14.sp,
                    fontFamily: fontRegular,
                    color: color210215.withAlpha(128)),
                inputStyle: lfTextStyle(sp: 14.sp, fontFamily: fontMedium),
                onChanged: (value) {},
              ),
              onTap: () {
                closeSoftKeyboard();
                _showBirthday(context);
              },
            ),
            40.h.sbh,
            Obx(() {
              var enable = true;
              if (logic.username.value.length < 2) {
                enable = false;
              }
              if (logic.username.value.length > 16) {
                enable = false;
              }
              if (logic.password.value.length < 6) {
                enable = false;
              }
              if (logic.password.value.length > 16) {
                enable = false;
              }
              if (logic.email.value.isEmail == false) {
                enable = false;
              }
              if (logic.birthday.value == null) {
                enable = false;
              }
              if (logic.gender.value == 0) {
                enable = false;
              }

              return LfButton(
                enabled: enable,
                text: strContinue.tr,
                onPress: () {
                  closeSoftKeyboard();
                  if (logic.email.value.isNotEmpty &&
                      (logic.email.value.indexOf('@') > 0)) {
                    var emailName = logic.email.value
                        .substring(0, logic.email.value.indexOf('@'));
                    if (logic.username.value.toUpperCase() ==
                        emailName.toUpperCase()) {
                      nameTips.value = strUsernameAndEmailTip.tr;
                      return;
                    }
                    checkName();
                  }
                },
              );
            })
          ],
        ),
      ),
    );
  }

  _showBirthday(BuildContext context) {
    DatePicker.showDatePicker(
      context,
      showTitleActions: true,
      minTime: _getMinDate(),
      maxTime: _getMaxDate(),
      currentTime: logic.birthday.value ??
          DateTime.now().subtract(const Duration(days: 366 * 24)),
      onChanged: (value) {},
      onConfirm: (value) {
        logic.birthday.value = value;
        logic.birthdayController.text =
            "${value.month}/${value.day}/${value.year}";
      },
      onCancel: () {},
      theme: MSDatePickerTheme(
        backgroundColor: color000000,
        doneStyle: lfTextStyle(
          sp: 15.sp,
        ),
        cancelStyle: lfTextStyle(
          sp: 15.sp,
        ),
        itemStyle: lfTextStyle(
          sp: 15.sp,
        ),
      ),
    );
  }

  _getMinDate() {
    var nowYear = DateTime.now().year;
    return DateTime(nowYear - 99, 1, 1);
  }

  _getMaxDate() {
    // var nowYear = DateTime.now().year;
    return DateTime.now().subtract(const Duration(days: 365 * 19 + 4));
  }

  checkName() {
    if (logic.username.value == logic.checkedUsername.value) {
      checkEmail(true);
    } else {
      showLoading();
      LfDio().get<LfBoolEntity>(
          url: apiCheckUserName,
          params: {"username": logic.username.value}).then((value) {
        logic.checkedUsername.value = logic.username.value;
        checkEmail(false);
      }, onError: (error) {
        hideLoading();
        if (error is NetError) {
          showSnackBar(error.msg);
        }
      });
    }
  }

  checkEmail(bool show) {
    if (logic.checkedEmail.value == logic.email.value) {
      hideLoading();
      logic.next();
    } else {
      if (show) {
        showLoading();
      }
      LfDio().get<LfBoolEntity>(
          url: apiCheckEmail,
          params: {"email": logic.email.value}).then((value) {
        hideLoading();
        logic.checkedEmail.value = logic.email.value;
        logic.next();
      }, onError: (error) {
        hideLoading();
        if (error is NetError) {
          showSnackBar(error.msg);
        }
      });
    }
  }
}
